#! /bin/bash -e

show_help(){
    echo
    echo " -----------------------------------------------"
    echo "NAME"
    echo "		collect_ap_for_ubuntu.sh"
    echo
    echo "SYNOPSIS"
    echo "		collect_ap_for_ubuntu.sh [OPTION]... --input-sysroot=<name> --output-dir=<name>"
    echo
    echo "DESRIPTION"
    echo "		Deployment FC to AP_HOME."
    echo
    echo "		--input-sysroot, -insys"
    echo "			Specify the sysroot to be used as input."
    echo
    echo "		--output-dir, -outd"
    echo "			Specify the directory to which AP_HOME will be output."
    echo
    echo "EXAMPLE"
    echo "		collect_ap_for_ubuntu.sh -insys=${AUBIST_AP_INSTALL_PATH}/functional_cluster_ubuntu/sysroot -outd=skeleton"
    echo
    echo " -----------------------------------------------"
    exit 0
}

show_invalid_option(){
    echo ""
    echo "Invalid option!"
    show_help
}

# parse options
for i in $*; do
    case "$i" in
        -insys=* | --input-sysroot=*)
            _IN_SYSROOT=${i#-*=}
            ;;
        -outd=* | --output-dir=*)
            _OUT_DIR=${i#-*=}
            ;;
        -h | --help)
            show_help
            ;;
        *)
            echo "unknown option '$i'"
            show_invalid_option
            usage 1
            ;;
    esac
done

if [ -z "$_IN_SYSROOT" ]; then
    echo "Specify the sysroot to be used as input.: -insys/--input-sysroot"
    exit 0
fi

if [ -z "$_OUT_DIR" ]; then
    echo "Specify the directory to which AP_HOME will be output. -outd/--output-dir"
    exit 0
fi

DIR="$( cd "$( dirname "$0" )" && pwd -P )"
COPY_APHOME=$(find ${DIR} -name copy_to_ap_home.sh)
if [ -z ${COPY_APHOME} ]; then
  echo -e "\033[31;1m[ERROR] No such file 'copy_to_ap_home.sh'.\033[m" 1>&2
  exit 1
fi

IN_SYSROOT="$(readlink -f ${_IN_SYSROOT})"
OUT_DIR="$(readlink -f ${_OUT_DIR})"

if [ -z ${OUT_DIR} ]; then
    mkdir -p ${_OUT_DIR}
    OUT_DIR="$(readlink -f ${_OUT_DIR})"
else
    rm -rf ${OUT_DIR}
    mkdir -p ${OUT_DIR}
fi

mkdir -p ${OUT_DIR}/opt/vrte/dev-aap-dlt/data/dlt-sockets
mkdir -p ${OUT_DIR}/opt/vrte/stm-project/data/

### create AP_HOME
pushd $(dirname $0)/internal > /dev/null
    bash ${COPY_APHOME} ${IN_SYSROOT} ${OUT_DIR} ${IN_SYSROOT}/target_vrteimage_info_ubuntu.json vrteimage
    ret=$?
popd > /dev/null

echo "[INFO] The copied files | folders are as follows:"
ls -l ${OUT_DIR}/opt/vrte

echo "[INFO] AP_HOME created."
